package com.lagou.config;

import com.lagou.io.Resources;
import com.lagou.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuild {
    private Configuration configuration;

    public XMLConfigBuild() {
        this.configuration = new Configuration();
    }

    public Configuration parseConfig(InputStream in) throws DocumentException {
        // 1.用dom4j来解析
        Document document = new SAXReader().read(in);
        // 2.拿到数据库配置文件跟sql对象
        // 2.1 拿到根节点 <configuration>
        Element rootElement = document.getRootElement();
        List<Element> list = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Element element:list){
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            // 把取到的参数封装到Properties中
            properties.setProperty(name,value);
        }
        // 创建c3p0链接池
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDataSourceName(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(comboPooledDataSource);

        // 解析mapper.xml:拿到路径--字节输入流--利用dom4j来进行解析
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for (Element element : mapperList) {
            // 通过key拿到value
            String resource = element.attributeValue("resource");
            // 创建字节输入流
            InputStream resourceAsSteam = Resources.getResourceAsSteam(resource);
            XMLMapperBuilder  xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(resourceAsSteam);

        }


        return configuration;
    }
}
